package com.ruoyix.weblog.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.ruoyix.common.core.controller.BaseController;
import com.ruoyix.common.core.domain.R;

import com.ruoyix.weblog.domain.UploadPO;
import com.ruoyix.weblog.service.IManageVideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

@RestController
@RequestMapping("/blog/video")
@CrossOrigin // 允许跨域
public class ManageVideoController extends BaseController {
    @Autowired
    private IManageVideoService manageVideoService;

    /**
     * 上传分片前校验文件是否存在
     *
     * @return
     */
    @GetMapping("/preUpload")
    public R<String> preUpload(@RequestParam("fileMd5") String fileMd5) {
        return manageVideoService.checkExists(fileMd5);
    }

    /**
     * 上传分片
     *
     * @return
     */
    @PostMapping("/upload")
    public R<String> fragmentation(@ModelAttribute UploadPO uploadPO) {
        return manageVideoService.uploadChunk(uploadPO);
    }

    @SaIgnore
    @GetMapping("/{m3u8}")
    public ResponseEntity<Resource> getM3u8Stream(@PathVariable String m3u8) throws IOException {
        // 这里假设m3u8文件在项目的resources目录下
        InputStream inputStream = Files.newInputStream(Paths.get("D:\\uploadTest\\video\\m3u8Dir\\3e7e81e7b0ee54c4ff66f1fb75e07254\\" + m3u8));
        Resource resource = new InputStreamResource(inputStream);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/vnd.apple.mpegurl"));
        headers.setContentDispositionFormData("attachment", "m3u8file.m3u8");

        return ResponseEntity.ok()
            .headers(headers)
            .body(resource);
    }
}

